/**
 * 
 */
package org.tio.im.server.demo.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.commons.lang3.StringUtils;
import org.tio.core.ChannelContext;
import org.tio.im.common.ImSessionContext;
import org.tio.im.common.cache.caffeine.CaffeineCacheManager;
import org.tio.im.common.packets.Group;
import org.tio.im.common.packets.LoginReqBody;
import org.tio.im.common.packets.User;
import org.tio.im.server.command.handler.proc.login.LoginCmdHandlerIntf;
import org.tio.im.server.util.AESCipher;
import org.tio.im.server.util.RedisUtil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
/**
 * @author WChao
 *
 */
public class UserServiceHandler implements LoginCmdHandlerIntf{
	private Logger log = LoggerFactory.getLogger(UserServiceHandler.class);
	private static final String cacheName = "default";
	public static final Map<String, User> tokenMap = new HashMap<>();


	/**
	 * 根据用户名和密码获取用户
	 * 
	 * @param loginname->存储的是 加密的 token
	 *            单程 账号 就是加密的串
	 * @param password 当成房间id
	 *            1 时当成是自己登陆
	 * @return
	 * @author: WChao
	 */
	public User getUser(String loginname, String password) {
		try {
			log.info("loginname:"+loginname+",password:"+password);
			User user = null;
			String token = AESCipher.aesCommDecrypt(loginname);
			if (token != null) {
				log.info("loginname destoken:"+token);
				String[] arr = token.split("_");
				long time = Long.parseLong(arr[1]);
				Date nowTime = new Date();
				long reduce = nowTime.getTime() - time;
				if (reduce < 600000000) {
				//if (reduce < 600000) {
					token = arr[0];
					if (token.startsWith("tp3")) {
						return null;
					}
					// 对方登录的用户--获取登录信息，登录了才能进来这里					
					JSONObject invitionbject = RedisUtil.getJsonInfo(token);
					if (invitionbject != null) {
						JSONObject jsonObject = invitionbject.getJSONObject("userEntity");
						if(jsonObject != null) {
							log.info(jsonObject.toJSONString());
							//登录信息处理
							user = this.getUser(jsonObject);
							Integer exam = jsonObject.getInteger("exam");
							if(exam != null && exam == 1) {
								JSONObject report = invitionbject.getJSONObject("report");
								if(report != null) {
									user.setYwScore(report.getInteger("ywScore"));
									user.setQgScore(report.getInteger("qgScore"));
									user.setXnScore(report.getInteger("xnScore"));
									user.setYzScore(report.getInteger("yzScore"));
									user.setMlScore(report.getInteger("mlScore"));
									user.setCharm(report.getDouble("charm"));
									user.setCompreAttr(report.getString("compreAttr"));
									user.setEasemobUser(report.getString("easemobUser"));
								}
							} 
						}
					}
				}
			}
			return user;
		} catch (Exception e) {
			log.error("登录异常：loginname:" + loginname, e);
		}
		return null;
	}
	/**
	 * 正式用户创建用户对象
	 * 
	 * @param jsonObject
	 * @return
	 * @author: WChao
	 */
	public User getUser(JSONObject jsonObject) {
		// demo中用map，生产环境需要用cache
		User user = new User();
		user.setId(jsonObject.getString("userId"));
		user.setNickName(jsonObject.getString("nickName"));
		user.setPhoto(jsonObject.getString("cover"));
		user.setAge(jsonObject.getInteger("age"));
		user.setGender(jsonObject.getInteger("gender"));
		return user;
	}
	/**
	 * 根据token获取用户信息
	 * @param token
	 * @return
	 * @author: WChao
	 */
	public User getUser(String token) {
		//demo中用map，生产环境需要用cache
		User user = null;
		try {
			 user = CaffeineCacheManager.getCache(cacheName).get(token,User.class);
		} catch (Exception e) {
			log.error("获取缓存信息失败",e);
		}
		return user;
	}
	public String newToken() {
		return UUID.randomUUID().toString();
	}	
	@Override
	public User getUser(LoginReqBody loginReqBody , ChannelContext channelContext) {
		String loginname = loginReqBody.getLoginname();
		String password = loginReqBody.getPassword();
		ImSessionContext imSessionContext = (ImSessionContext)channelContext.getAttribute();
		String handshakeToken = imSessionContext.getToken();
		User user = null;
		if (!StringUtils.isBlank(handshakeToken)) {
			user =  this.getUser(handshakeToken);
			if(user == null || StringUtils.isBlank(user.getId())) {
				user = this.getUser(loginname, password);
			}
		}else {
			user = this.getUser(loginname, password);
			//生成token
			handshakeToken = this.newToken();
			imSessionContext.setToken(handshakeToken);
		}
		if(user != null) {
			user.setGroups(this.makeUserGroup(password));			
			try {
				CaffeineCacheManager.getCache(cacheName).put(handshakeToken, user);
			} catch (Exception e) {
				log.error("设置缓存信息失败",e);
			}
		}
		return user;
	}
	private List<Group> makeUserGroup(String password){
		List<Group> groups = null;
		try {
			//解锁用户房间id
			String roomInfo = AESCipher.aesWxCommDecrypt(password);
			JSONObject roomObject = JSON.parseObject(roomInfo);
			String roomId = roomObject.getString("shopId");
			String roomName = roomObject.getString("shopName");
			//用户加入组
			 groups = this.initGroups(roomId, roomName);
		} catch (Exception e) {
			log.error("解密组异常", e);
		}
		return groups;
	}
	private List<Group> initGroups(String roomId, String nickName) {
		// 模拟的群组;正式根据业务去查数据库或者缓存;
		List<Group> groups = new ArrayList<Group>();
		groups.add(new Group(roomId, nickName));
		return groups;
	}	
	@Override
	public boolean isProtocol(ChannelContext channelContext) {		 
		return true;
	}
	@Override
	public String name() {		
		return "default";
	}
}
